#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <time.h>
#include "TLogger.h"

Logger::Logger(char* filePath)
{
    logFileTime_ = 0;
    logFile_ = NULL;
    strcpy(filePath_, filePath);
}

Logger::~Logger()
{
    if (logFile_)
    {
        fclose(logFile_);
        logFile_ = NULL;
    }
}

void Logger::OpenFile(char* file)
{

    if (logFile_)
    {
        fclose(logFile_);
        logFile_ = NULL;
    }
    logFile_ = fopen(file,"a + ");
    fprintf(logFile_,"\n\n");
    fprintf(logFile_,"====================================================\n");
    fprintf(logFile_,"====================STARTRUN========================\n");
    fprintf(logFile_,"====================================================\n");
    fprintf(logFile_,"\n\n");
}

void Logger::WriteLog(const char* level, const char* fmt, ...)
{
    std::lock_guard<std::mutex> lock(mutex_);
    va_list args;
    va_start(args, fmt);
    vsprintf(writeBuf_, fmt, args);
    va_end(args);

    time_t atimer = time(NULL);
    struct tm* area = localtime(&atimer);
    int time = ((area->tm_year + 1900)*100)
               + ((area->tm_mon + 1)*10000)
               + (area->tm_mday*100)
               + area->tm_hour;

    if (logFileTime_ < time)
    {
        logFileTime_ = time;
        char file[256];
        sprintf(file, "%s_%04d%02d%02d%02d.log", filePath_, area->tm_year + 1900, area->tm_mon + 1, area->tm_mday,area->tm_hour);
        OpenFile(file);
    }
    fprintf(logFile_, "%04d-%02d-%02d %02d:%02d:%02d TID:%05d %5s - %s\n", area->tm_year + 1900, area->tm_mon + 1, area->tm_mday, area->tm_hour, area->tm_min, area->tm_sec, 0, level, writeBuf_);
    fflush(logFile_);
}

